# -*- coding:utf-8 -*-
from tornado import gen
import hashlib, json
import StringIO
import xlwt

from appcommon.framework import WebBaseHandler
from common import utiltool
import tools
import settings
from common import config, timetool
import models


class LoginHandler(WebBaseHandler):
    """
    登录
    """
    # @decorator.check_params(['product_type', 'class_id', 'site_id'])
    # @decorator.verify_params
    @gen.coroutine
    def get(self):
        if self.current_user:
            self.redirect('/')
        else:
            self.render('login.html', code='0')

    @gen.coroutine
    def post(self):
        user_name = self.get_argument('username', '')
        password = self.get_argument('pwd', '')
        pwdtmp = hashlib.md5()
        pwdtmp.update(password)
        md5pwd = pwdtmp.hexdigest()
        auth = yield tools.authenticate(user_name, md5pwd)
        if auth:
            self.set_secure_cookie("user_name", user_name, 1)
            self.set_secure_cookie("access_token", '0', 1)
            utiltool.response_write(self, {'code': '0', 'msg': u'success'})

        else:
            utiltool.response_write(self, {'code': '1004', 'msg': u'用户名或密码输入有误，请确认'})


class LogoutHandler(WebBaseHandler):
    """
    登出
    """
    # @decorator.check_params(['product_type', 'class_id', 'site_id'])
    # @decorator.verify_params
    @gen.coroutine
    def post(self):
        user = self.current_user
        if user:
            self.clear_cookie('user_name')
            self.clear_cookie('access_token')
            utiltool.response_write(self, {'code': '0'})
        else:
            utiltool.response_write(self, {'code': '1'})


class IndexHandler(WebBaseHandler):
    """
    首页
    """
    # @decorator.check_params(['product_type', 'class_id', 'site_id'])
    # @decorator.verify_params
    @gen.coroutine
    def get(self):
        if self.current_user:
            menu_list = yield models.get_menu_tree()
            menu_list.append(dict(
                menu_name=u"菜单管理",
                link_list=[{'link_name': u"菜单管理", 'link': '/menu_manage.html'}]
            ))
            self.render('index.html', menu_list=menu_list, user_name=self.current_user['user_name'])
        else:
            self.render('login.html', code='0')


class MenuManageHandler(WebBaseHandler):
    """
    菜单管理
    """
    # @decorator.check_params(['product_type', 'class_id', 'site_id'])
    # @decorator.verify_params
    @gen.coroutine
    def get(self):
        menu_type = self.get_argument('menu_type', '0')
        parent_id = self.get_argument('parent_id', '-1')
        left = self.get_argument('left', '')
        menu_list = yield models.get_manage_menu(menu_type, parent_id, left)
        utiltool.response_write(self, menu_list)


class UpdateMenuHandler(WebBaseHandler):
    """
    菜单管理
    """
    @gen.coroutine
    def post(self, ex=None):
        dic = self.request.arguments
        for k in dic.iterkeys():
            dic[k] = dic[k][0]
        try:
            yield models.update_manage_menu(dic)
            res = {'code': '0', 'msg': u'保存成功'}
        except ex:
            res = {'code': '1', 'msg': u'保存失败'}
        utiltool.response_write(self, res)


class DelMenuHandler(WebBaseHandler):
    """
    菜单管理
    """
    @gen.coroutine
    def post(self, ex=None):
        menu_id = self.get_argument('menu_id', '')
        try:
            yield models.del_manage_menu(menu_id)
            res = {'code': '0', 'msg': u'删除成功'}
        except ex:
            res = {'code': '1', 'msg': u'删除失败'}
        utiltool.response_write(self, res)



class VipUserInfoHandler(WebBaseHandler):
    """
    获取用户vip教练等信息
    """
    @gen.coroutine
    def get(self):
        current_time = timetool.get_timestamp()
        phone = self.get_argument('phone', '')
        rows = self.get_argument('rows', '')
        page = self.get_argument('page', '')
        if phone:
            vip_info = yield models.check_phone_is_vip(phone, current_time)
            user_info = yield models.get_user_info_with_phone(phone)
            vip_end = timetool.convert_timestamp_to_date(vip_info['vip_end']) if vip_info['vip_end'] else ""
            res = dict(
                rows=[{"phone": phone,
                       "is_vip": vip_info['is_vip'],
                       "vip_end": vip_end,
                       "avatar" : user_info['avatar'] if user_info else "",
                       "nick_name" : user_info['nick_name'] if user_info else ""
                       }],
                total=1
            )
        else:
            info_list = yield models.get_vip_user_list()
            start = (int(page) - 1) * int(rows)
            info = info_list[start:start + int(rows)]
            for item in info:
                item['is_vip'] = 1 if item['is_vip'] else 0
                item['vip_end'] = timetool.convert_timestamp_to_date(item['vip_end']) if item['vip_end'] else ""
            res = dict(rows=info, total=len(info_list))
        utiltool.response_write(self, res)



class UpdateVipUserHandler(WebBaseHandler):
    """
    """
    @gen.coroutine
    def post(self):
        current_time = timetool.get_timestamp()
        phone = self.get_argument('phone', '')
        is_vip = self.get_argument('is_vip', '0')
        is_couch = self.get_argument('is_couch', '0')
        vip_end1 = self.get_argument('vip_end', '')
        vip_end = timetool.convert_date_to_timestamp(vip_end1)
        yield models.del_vip_user(phone)
        if is_vip == "1":
            yield models.add_vip_user(phone, current_time, vip_end)
        res = {"code": "0", "msg": u"修改成功"}
        utiltool.response_write(self, res)


class Vip4UserInfoHandler(WebBaseHandler):
    """
    获取用户vip4
    """
    @gen.coroutine
    def get(self):
        current_time = timetool.get_timestamp()
        phone = self.get_argument('phone', '')
        rows = self.get_argument('rows', '')
        page = self.get_argument('page', '')
        if phone:
            vip_info = yield models.check_phone_is_vip4(phone, current_time)
            user_info = yield models.get_user_info_with_phone(phone)
            vip_end = timetool.convert_timestamp_to_date(vip_info['vip_end']) if vip_info['vip_end'] else ""
            res = dict(
                rows=[{"phone": phone,
                       "is_vip": vip_info['is_vip'],
                       "vip_end": vip_end,
                       "avatar" : user_info['avatar'] if user_info else "",
                       "nick_name" : user_info['nick_name'] if user_info else ""
                       }],
                total=1
            )
        else:
            info_list = yield models.get_vip4_user_list()
            start = (int(page) - 1) * int(rows)
            info = info_list[start:start + int(rows)]
            for item in info:
                item['is_vip'] = 1 if item['is_vip'] else 0
                item['vip_end'] = timetool.convert_timestamp_to_date(item['vip_end']) if item['vip_end'] else ""
            res = dict(rows=info, total=len(info_list))
        utiltool.response_write(self, res)



class UpdateVip4UserHandler(WebBaseHandler):
    """设置vip4
    """
    @gen.coroutine
    def post(self):
        current_time = timetool.get_timestamp()
        phone = self.get_argument('phone', '')
        is_vip = self.get_argument('is_vip', '0')
        is_couch = self.get_argument('is_couch', '0')
        vip_end1 = self.get_argument('vip_end', '')
        vip_end = timetool.convert_date_to_timestamp(vip_end1)
        yield models.del_vip4_user(phone)
        if is_vip == "1":
            yield models.add_vip4_user(phone, current_time, vip_end)
        res = {"code": "0", "msg": u"修改成功"}
        utiltool.response_write(self, res)


class BmtListHandler(WebBaseHandler):
    """
    报名通列表
    """
    @gen.coroutine
    def get(self):
        current_time = timetool.get_timestamp()
        phone = self.get_argument('phone', '')
        rows = self.get_argument('rows', '')
        page = self.get_argument('page', '')
        if phone:
            vip_info = yield models.check_phone_is_bmt(phone, current_time)
            user_info = yield models.get_user_info_with_phone(phone)
            vip_end = timetool.convert_timestamp_to_date(vip_info['vip_end']) if vip_info['vip_end'] else ""
            res = dict(
                rows=[{"phone": phone,
                       "is_vip": vip_info['is_vip'],
                       "vip_end": vip_end,
                       "avatar": user_info['avatar'] if user_info else "",
                       "nick_name": user_info['nick_name'] if user_info else ""
                       }],
                total=1
            )
        else:
            info_list = yield models.get_bmt_user_list()
            start = (int(page) - 1) * int(rows)
            info = info_list[start:start + int(rows)]
            for item in info:
                item['is_vip'] = 1 if item['is_vip'] else 0
                item['vip_end'] = timetool.convert_timestamp_to_date(item['vip_end']) if item['vip_end'] else ""
            res = dict(rows=info, total=len(info_list))
        utiltool.response_write(self, res)



class SetBmtHandler(WebBaseHandler):
    """设置报名通
    """
    @gen.coroutine
    def post(self):
        current_time = timetool.get_timestamp()
        phone = self.get_argument('phone', '')
        is_vip = self.get_argument('is_vip', '0')
        vip_end1 = self.get_argument('vip_end', '')
        vip_end = timetool.convert_date_to_timestamp(vip_end1)
        yield models.del_bmt_user(phone)
        if is_vip == "1":
            yield models.add_bmt_user(phone, current_time, vip_end)
        res = {"code": "0", "msg": u"修改成功"}
        utiltool.response_write(self, res)


class CouchUserInfoHandler(WebBaseHandler):
    """
    获取用户vip教练等信息
    """
    @gen.coroutine
    def get(self):
        phone = self.get_argument('phone', '')
        rows = self.get_argument('rows', '')
        page = self.get_argument('page', '')
        info_list = yield models.get_couch_user_list(phone)
        start = (int(page) - 1) * int(rows)
        info = info_list[start:start + int(rows)]
        res = dict(rows=info, total=len(info_list))
        utiltool.response_write(self, res)


class ScoreListHandler(WebBaseHandler):
    """
    """
    @gen.coroutine
    def get(self):
        phone = self.get_argument('phone', '')
        page = self.get_argument('page', '')
        rows = self.get_argument('rows', '')
        info_list = yield models.get_score_list(phone)
        start = (int(page) - 1) * int(rows)
        info = info_list[start:start + int(rows)]
        for item in info:
            pass
        res = dict(rows=info, total=len(info_list))
        utiltool.response_write(self, res)


class ScoreDetailHandler(WebBaseHandler):
    """
    """
    @gen.coroutine
    def get(self):
        phone = self.get_argument('phone', '')
        page = self.get_argument('page', '')
        rows = self.get_argument('rows', '')
        info_list = yield models.get_score_detail(phone)
        start = (int(page) - 1) * int(rows)
        info = info_list[start:start + int(rows)]
        for item in info:
            item['pubtime'] = timetool.convert_timestamp_to_date(item['pubtime']) if item['pubtime'] else ""
            if item['type'] == 0:  # 减
                item['desc'] = u"提现"
                item['score'] = 0 - item['score']
                item['avatar'] = "http://app.qcjkjg.com/media/img/avatar/ic_tixian.png"
            elif item['type'] in [1, 5]:  # 邀请好友
                from_info = yield models.get_user_info_with_phone(item['from_phone'])
                nick_name = from_info['nick_name'] if from_info else ""
                item['desc'] = u"邀请好友:{} {}".format(nick_name, item['from_phone'])
                item['avatar'] = from_info['avatar'] if from_info else "http://app.qcjkjg.com/media/img/avatar/default.png"
            elif item['type'] == 2:  # 分享
                item['desc'] = u"分享奖励"
                item['avatar'] = "http://app.qcjkjg.com/media/img/avatar/ic_share_1.png"
            elif item['type'] == 3:  # 后台加
                item['avatar'] = "http://app.qcjkjg.com/media/img/avatar/ic_share_1.png"
            else:  # 后台减
                item['score'] = 0 - item['score']
                item['avatar'] = "http://app.qcjkjg.com/media/img/avatar/ic_tixian.png"
        res = dict(rows=info, total=len(info_list))
        utiltool.response_write(self, res)


class PriceListHandler(WebBaseHandler):
    """订单价格列表
    """
    @gen.coroutine
    def get(self):
        info = yield models.get_price_list()
        res = dict(rows=info, total=len(info))
        utiltool.response_write(self, res)


class UpdatePriceHandler(WebBaseHandler):
    """修改价格
    """
    @gen.coroutine
    def post(self):
        order_type = self.get_argument('order_type', '')
        price = self.get_argument('price', '')
        youhui_price = self.get_argument('youhui_price', '')
        yield models.update_price(order_type, price, youhui_price)
        res = {"code": "0", "msg": u"修改成功"}
        utiltool.response_write(self, res)


class ChangeScoreHandler(WebBaseHandler):
    """手动调整积分
    """
    @gen.coroutine
    def post(self):
        phone = self.get_argument('phone', '')
        score = self.get_argument('score', '')
        type = self.get_argument('type', '')
        desc = self.get_argument('desc', '')
        current_time = timetool.get_timestamp()
        action = 'add' if type == '3' else 'min'
        yield models.update_score_2_mysql(phone, action, float(score))
        yield models.save_score_log(phone, score, type, current_time, desc)
        res = {"code": "0", "msg": u"修改成功"}
        utiltool.response_write(self, res)


class GetCouchAuthHandler(WebBaseHandler):
    """获取教练认证状态
    """
    @gen.coroutine
    def get(self):
        phone = self.get_argument('phone', '')
        info = yield models.get_couch_auth(phone)
        res = {"code": "0", "info": info}
        utiltool.response_write(self, res)


class SetCouchAuthHandler(WebBaseHandler):
    """修改教练认证状态
    """
    @gen.coroutine
    def post(self):
        phone = self.get_argument('phone', '')
        ztype = self.get_argument('ztype', 'jlz')
        status = self.get_argument('status', '1')
        yield models.set_couch_auth(phone, ztype, status)
        info = yield models.get_couch_auth(phone)
        auth_cnt = models.check_couch_auth_cnt(info)
        status_quan = 1 if auth_cnt >= 3 else 0
        yield models.set_couch_auth_status(phone, status_quan)
        res = {"code": "0", "msg": u"审核成功"}
        utiltool.response_write(self, res)


class ExportAllUsersHandler(WebBaseHandler):
    """导出所有用户信息
    """
    @gen.coroutine
    def get(self):
        info = yield models.get_all_user_info()
        s = StringIO.StringIO()
        f = xlwt.Workbook()  # 创建工作簿
        sheet1 = f.add_sheet(u'sheet1', cell_overwrite_ok=True)  # 创建sheet
        row0 = [u'手机号', u'昵称', u'头像', u'金额', u'驾校地区', u'驾校',
                u'是否VIP', u'是否认证教练', u'性别', u'教练信息电话',
                u'教练信息地址', u'教练信息驾校', u'教练驾龄', u'教练车型',
                u'教练积分', u'是否开通报名通', u'地区']
        current_time = timetool.get_timestamp()
        # 生成第一行
        for i in range(0, len(row0)):
            sheet1.write(0, i, row0[i])
        for i in range(0, len(info)):
            sheet1.write(i + 1, 0, info[i]['phone'])
            sheet1.write(i + 1, 1, info[i]['nick_name'])
            sheet1.write(i + 1, 2, info[i]['avatar'])
            sheet1.write(i + 1, 3, info[i]['money'])
            sheet1.write(i + 1, 4, info[i]['school_area'])
            sheet1.write(i + 1, 5, info[i]['school'])
            vip = u'是' if info[i]['vip'] and info[i]['vip'] > current_time else u'否'
            sheet1.write(i + 1, 6, vip)
            if info[i]['status'] == 0:
                auth = u'未认证'
            elif info[i]['status'] == 1:
                auth = u'已认证'
            else:
                auth = info[i]['status']
            sheet1.write(i + 1, 7, auth)
            sex = u'男' if info[i]['sex'] == 'male' else u'女'
            sheet1.write(i + 1, 8, sex)
            sheet1.write(i + 1, 9, info[i]['tel'])
            sheet1.write(i + 1, 10, info[i]['couch_area'])
            sheet1.write(i + 1, 11, info[i]['couch_school'])
            sheet1.write(i + 1, 12, info[i]['years'])
            sheet1.write(i + 1, 13, info[i]['car_type'])
            sheet1.write(i + 1, 14, info[i]['score'])
            bmt = u'是' if info[i]['bmt'] and info[i]['bmt'] > current_time else u'否'
            sheet1.write(i + 1, 15, bmt)
            sheet1.write(i + 1, 16, info[i]['area'])

        f.save(s)  # 保存文件
        s.seek(0)

        filename = u"用户信息.xls"
        self.set_header('Content-Type', 'application/octet-stream')
        self.set_header('Content-Disposition', 'attachment; filename=' + filename)
        buf_size = 4096
        while True:
            data = s.read(buf_size)
            if not data:
                break
            self.write(data)
        self.finish()


class GetBaseCntHandler(WebBaseHandler):
    """获取人数基数
    """
    @gen.coroutine
    def get(self):
        info = yield models.get_base_cnt()
        res = dict(rows=info, total=len(info))
        utiltool.response_write(self, res)


class SetBaseCntHandler(WebBaseHandler):
    """设置人数基数
    """
    @gen.coroutine
    def post(self):
        vip_base_cnt = self.get_argument('vip_base_cnt', '')
        student_base_cnt = self.get_argument('student_base_cnt', '')
        yield models.update_base_cnt(vip_base_cnt, student_base_cnt)
        res = {"code": "0", "msg": u"修改成功"}
        utiltool.response_write(self, res)


class CouchScoreListHandler(WebBaseHandler):
    """
    """
    @gen.coroutine
    def get(self):
        phone = self.get_argument('phone', '')
        page = self.get_argument('page', '')
        rows = self.get_argument('rows', '')
        info_list = yield models.get_couch_score_list(phone)
        start = (int(page) - 1) * int(rows)
        info = info_list[start:start + int(rows)]
        res = dict(rows=info, total=len(info_list))
        utiltool.response_write(self, res)


class CouchScoreDetailHandler(WebBaseHandler):
    """
    """
    @gen.coroutine
    def get(self):
        phone = self.get_argument('phone', '')
        page = self.get_argument('page', '')
        rows = self.get_argument('rows', '')
        info_list = yield models.get_couch_score_detail(phone)
        start = (int(page) - 1) * int(rows)
        info = info_list[start:start + int(rows)]
        for item in info:
            item['pubtime'] = timetool.convert_timestamp_to_date(item['pubtime'])
            if item['type'] == 'sign':
                item['type'] = u"签到"
            elif item['type'] == 'share':
                item['type'] = u"分享邀请学员"
            elif item['type'] == 'card':
                item['type'] = u"生成名片"
            elif item['type'] == 'follow':
                item['type'] = u"学员关注"
            elif item['type'] == 'evaluate':
                item['type'] = u"学员评价"
            elif item['type'] == 'open_bmt':
                item['type'] = u"开通报名通"
        res = dict(rows=info, total=len(info_list))
        utiltool.response_write(self, res)


class GetScoreConfHandler(WebBaseHandler):
    """奖金设置
    """
    @gen.coroutine
    def get(self):
        info = yield models.get_score_conf()
        res = dict(rows=info, total=len(info))
        utiltool.response_write(self, res)


class SetScoreConfHandler(WebBaseHandler):
    """奖金设置
    """
    @gen.coroutine
    def post(self):
        user_type = self.get_argument('user_type', '')
        source = self.get_argument('source', '')
        score = self.get_argument('score', '')
        yield models.set_score_conf(user_type, source, score)
        res = {"code": "0", "msg": u"修改成功"}
        utiltool.response_write(self, res)